<template>
  <div class="interview-problem-description">
    <el-tabs type="border-card" v-model="activeTab">
      <el-tab-pane label="题目列表" name="tabList">
        <el-table :data="problemData" style="width: 100%" :stripe="true">
          <el-table-column prop="id" label="#" width="80"> </el-table-column>
          <el-table-column prop="title" label="题目" width="200">
            <template slot-scope="scope">
              <el-link type="primary" @click="onProblemClick(scope.row)">
                {{ scope.row.title }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="difficulty" label="难度"> </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane
        label="题目内容"
        name="tabDescription"
        :disabled="isDescriptionDisabled"
      >
        <el-form :model="problem" label-width="80px">
          <el-form-item label="题目名称">
            <div
              style="
                background-color: #f6f6f6;
                padding: 0 20px;
                border-radius: 4px;
              "
            >
              {{ this.problem.title }}
            </div>
          </el-form-item>
          <el-form-item label="题目难度">
            <el-rate
              v-if="problem.difficulty"
              v-model="problem.difficulty"
              :max="3"
              :texts="['简单', '中等', '困难']"
              show-text
              disabled
            ></el-rate>
            <el-tag v-else disable-transitions>待定</el-tag>
          </el-form-item>
          <el-form-item label="题目描述">
            <div
              style="
                background-color: #f6f6f6;
                padding: 0 20px;
                border-radius: 4px;
              "
            >
              {{ problem.content }}
            </div>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane
        label="面试官选项"
        :disabled="isInterviewee"
        name="tabInterviewerOption"
      >
        <el-table :data="problemData" style="width: 100%" :stripe="true">
          <el-table-column prop="id" label="#" width="80"> </el-table-column>
          <el-table-column prop="title" label="题目" width="200">
            <template slot-scope="scope">
              <el-link type="primary" @click="onProblemClick(scope.row)">
                {{ scope.row.title }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="difficulty" label="难度"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="onProblemRemove(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row>
          <el-col :span="4" :offset="0">
            <el-button type="primary" @click="onInterviewProblemUpdate">
              更换题目
            </el-button>
          </el-col>
          <el-col :span="4" :offset="0">
            <el-button type="danger" @click="onInterviewFinish">
              结束面试
            </el-button>
          </el-col>
          <el-col :span="12" :offset="2">
            <span>当前观看：</span>
            <el-select
              class="interviewer-select"
              v-model="interviewee"
              placeholder="请选择要观看的面试者"
              @change="onIntervieweeChange"
              @visible-change="onIntervieweeSelectClick"
            >
              <el-option
                v-for="user in userData"
                :key="user._id"
                :label="user.username"
                :value="user._id"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" :offset="10">
            <span>面试邀请码：</span>
            <el-tag>
              {{ this.inviteCode }}
            </el-tag>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      title="删除题目"
      :visible.sync="dialogRemoveVisible"
      :before-close="beforeDialogRemoveClose"
      append-to-body
    >
      <span>确认删除此问题？</span>
      <div slot="footer">
        <el-button @click="onProblemRemoveCancel">取消</el-button>
        <el-button type="primary" @click="onProblemRemoveConfirm"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="选择题目"
      :visible.sync="dialogSelectVisiable"
      :before-close="beforeDialogSelectClose"
      append-to-body
    >
      <interviewer-public-problem-set
        ref="publicProblem"
        @onPublicProblemSelectionChange="onPublicProblemSelectionChange"
      ></interviewer-public-problem-set>
      <interviewer-self-problem-set
        ref="selfProblem"
        @onSelfProblemSelectionChange="onSelfProblemSelectionChange"
      ></interviewer-self-problem-set>
      <div slot="footer">
        <el-button @click="onProblemSelectCancel">取消</el-button>
        <el-button type="primary" @click="onProblemSelectConfirm"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
import InterviewerPublicProblemSet from "@/components/Interviewer/InterviewerPublicProblemSet.vue";
import InterviewerSelfProblemSet from "@/components/Interviewer/InterviewerSelfProblemSet.vue";
export default {
  name: "InterviewProblemDescription",
  components: {
    InterviewerPublicProblemSet,
    InterviewerSelfProblemSet,
  },
  mounted() {
    this.judgeInterviewee();
    this.onIntervieweeEnter();
    this.getProblemData();
    this.judgeInterviewFinished();
  },
  destroyed() {
    clearTimeout(this.timeoutId);
  },
  methods: {
    judgeInterviewFinished() {
      if (this.isInterviewee) {
        let roomId = this.$route.params.rid;
        let that = this;
        let getInterviewFinishStatus = function() {
          axios
            .get("/api/room/finished", {
              params: {
                rid: roomId,
              },
            })
            .then((response) => {
              // console.log(response);
              if (response.data.result.finished == 1) {
                that.$message.warning("面试已结束，跳转到首页");
                that.$router.push("/problem");
              } else {
                that.timeoutId = setTimeout(getInterviewFinishStatus, 1000);
                // console.log("that.timeoutId", that.timeoutId);
              }
            })
            .catch((error) => {
              console.log(error);
              this.$message.error("面试未成功结束");
            });
        };
        this.timeoutId = setTimeout(getInterviewFinishStatus, 1000);
      }
    },
    onIntervieweeSelectClick(visible) {
      if (visible) {
        //请求用户列表存入userData
        let roomId = this.$route.params.rid;
        axios
          .get("/api/room/intervieweeall", {
            params: {
              rid: roomId,
            },
          })
          .then((response) => {
            console.log(response);
            this.userData = response.data.result.intervieweeSet;
          })
          .catch((error) => {
            console.log(error);
          });
      } else {
        // this.setUserDataDefault();
      }
    },
    onIntervieweeEnter() {
      if (this.isInterviewee) {
        let roomId = this.$route.params.rid;
        axios
          .get("/api/room/enter", {
            params: {
              rid: roomId,
            },
          })
          .then((response) => {
            console.log(response);
            const name = window.sessionStorage.getItem("username");
            this.$message.success("面试者" + name + "进入房间成功");
          })
          .catch((error) => {
            console.log(error);
            const name = window.sessionStorage.getItem("username");
            this.$message.error("面试者" + name + "未进入房间");
          });
      }
    },
    onIntervieweeChange(userId) {
      this.$emit("onIntervieweeChange", userId);
    },
    judgeInterviewee() {
      const type = window.sessionStorage.getItem("usertype");
      if (type != 1) {
        this.isInterviewee = true;
      } else {
        this.isInterviewee = false;
        let roomId = this.$route.params.rid;
        this.inviteCode = roomId;
      }
    },
    setUserDataDefault() {
      this.userData = [
        {
          username: "user1",
          _id: "111",
          status: 1,
        },
        {
          username: "user2",
          _id: "222",
          status: 1,
        },
        {
          username: "user3",
          _id: "333",
          status: 1,
        },
      ];
    },
    setDoc() {
      let roomId = this.$route.params.rid;
      for (let i = 0; i < this.problemData.length; i++) {
        for (let j = 0; j < this.userData.length; j++) {
          let docname =
            roomId + "/" + this.userData[j]._id + "/" + this.problemData[i]._id;
          this.doc.push(docname);
        }
      }
      for (let i = 0; i < this.problemData.length; i++) {
        for (let j = 0; j < this.userData.length; j++) {
          let docname =
            roomId + "/" + this.userData[j]._id + "/" + this.problemData[i]._id;
          this.doc_clear.push(docname);
        }
      }
      for (let j = 0; j < this.userData.length; j++) {
        let docname = roomId + "/" + this.userData[j]._id + "/0";
        this.doc_clear.push(docname);
      }
    },
    setProblemDefault() {
      this.problem = {
        _id: "",
        title: "",
        difficulty: 0,
        content: "",
        status: 0,
      };
    },
    getProblemData() {
      let roomId = this.$route.params.rid;
      axios
        .get("/api/room/problemall", {
          params: {
            rid: roomId,
          },
        })
        .then((response) => {
          console.log(response);
          if (response.data.status == 1) {
            this.problemData = response.data.result.problemSet;
            if (this.problemData.length) {
              this.problemData.forEach((problem, index) => {
                problem["id"] = index + 1;
              });
            }
            this.$message.success("获取面试题目成功");
            this.$emit("deliverProblemData", this.problemData);
          }
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("获取面试题目失败");
          this.$emit("deliverProblemData", this.problemData);
        });
    },
    clearProblemSelection() {
      this.publicProblemSelection = [];
      this.selfProblemSelection = [];
      this.$refs["publicProblem"].clearSelection();
      this.$refs["selfProblem"].clearSelection();
    },
    onProblemClick(row) {
      this.problem = JSON.parse(JSON.stringify(row));
      this.isDescriptionDisabled = false;
      this.activeTab = "tabDescription";
    },
    onInterviewFinish() {
      //面试结束，房间信息保存，生成历史信息
      this.setDoc();
      let roomId = this.$route.params.rid;
      axios
        .get("/api/room/finish", {
          params: {
            rid: roomId,
          },
        })
        .then((response) => {
          console.log(response);
          this.$message.success("面试已结束，跳转到管理界面");
          this.$router.push("/interviewer");
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("面试未成功结束");
        });
      axios
        .post("/api/docTransfer/moveMany", {
          params: {
            docNames: this.doc,
          },
        })
        .then((response) => {
          console.log(response);
          // this.$message.success("面试结束");
        })
        .catch((error) => {
          console.log(error);
          // this.$message.error("面试未成功结束");
        });
      axios
        .post("/api/docTransfer/clearMany", {
          params: {
            dropCollections: this.doc_clear,
          },
        })
        .then((response) => {
          console.log(response);
          // this.$message.success("面试结束");
        })
        .catch((error) => {
          console.log(error);
          // this.$message.error("面试未成功结束");
        });
      this.$emit("onInterviewFinish");
    },
    beforeDialogRemoveClose(done) {
      this.setProblemDefault();
      done();
    },
    beforeDialogSelectClose(done) {
      this.clearProblemSelection();
      done();
    },
    onPublicProblemSelectionChange(selection) {
      this.publicProblemSelection = selection;
    },
    onSelfProblemSelectionChange(selection) {
      this.selfProblemSelection = selection;
    },
    onProblemRemove(row) {
      this.problem = JSON.parse(JSON.stringify(row));
      this.dialogRemoveVisible = true;
    },
    onProblemRemoveCancel() {
      this.dialogRemoveVisible = false;
      this.setProblemDefault();
    },
    onProblemRemoveConfirm() {
      let roomId = this.$route.params.rid;
      //数据库删除操作
      axios
        .get("/api/room/deleteproblem", {
          params: {
            rid: roomId,
            pid: this.problem._id,
          },
        })
        .then((response) => {
          console.log(response);
          this.dialogRemoveVisible = false;
          this.setProblemDefault();
          this.getProblemData();
          this.$message.success("删除题目成功");
        })
        .catch((error) => {
          console.log(error);
          this.dialogRemoveVisible = false;
          this.setProblemDefault();
          this.$message.error("删除题目失败");
        });
    },
    onInterviewProblemUpdate() {
      this.onProblemSelect();
    },
    onProblemSelect() {
      this.dialogSelectVisiable = true;
      this.$nextTick(() => {
        let problemDataCopy = JSON.parse(JSON.stringify(this.problemData));
        this.$refs["publicProblem"].setAlreadySelection(problemDataCopy);
        this.$refs["selfProblem"].setAlreadySelection(problemDataCopy);
      });
    },
    onProblemSelectCancel() {
      this.dialogSelectVisiable = false;
      this.clearProblemSelection();
    },
    onProblemSelectConfirm() {
      let problemData = this.problemSelection.slice();
      if (problemData.length === 0) {
        this.$message.warning("未选择任何题目");
      } else {
        this.dialogSelectVisiable = false;
        let roomId = this.$route.params.rid;
        let interviewProblemDataId = problemData.map((problem) => {
          return problem._id;
        });
        axios
          .post("/api/room/updateproblem", {
            rid: roomId,
            problemSet: interviewProblemDataId,
          })
          .then((response) => {
            console.log(response);
            this.$message.success("更换面试题目成功");
            this.getProblemData();
          })
          .catch((error) => {
            console.log(error);
            this.$message.error("更换面试题目失败");
          });
        this.clearProblemSelection();
      }
    },
  },
  data() {
    return {
      doc: [],
      doc_clear: [],
      activeTab: "tabList",
      dialogRemoveVisible: false,
      dialogSelectVisiable: false,
      publicProblemSelection: [],
      selfProblemSelection: [],
      isDescriptionDisabled: true,
      isInterviewee: false,
      inviteCode: "",
      interviewee: "",
      timeoutId: "",
      userData: [],
      // userData: [
      //   {
      //     username: "user1",
      //     _id: "111",
      //     status: 1,
      //   },
      //   {
      //     username: "user2",
      //     _id: "222",
      //     status: 1,
      //   },
      //   {
      //     username: "user3",
      //     _id: "333",
      //     status: 1,
      //   },
      // ],
      problem: {
        _id: "",
        title: "",
        difficulty: 0,
        content: "",
        status: 0,
      },
      problemData: [],
    };
  },
  computed: {
    problemSelection() {
      return this.publicProblemSelection.concat(this.selfProblemSelection);
    },
  },
};
</script>
<style scoped></style>
